import { Context } from "jsr:@oak/oak/context";
import { Next } from "jsr:@oak/oak/middleware";
import { getAuth } from "../services/auth.ts";
import { AuthErrors } from "../errors/AppError.ts";

export async function authMiddleware(ctx: Context, next: Next) {
  const authHeader = ctx.request.headers.get("Authorization");
  
  if (!authHeader?.startsWith("Bearer ")) {
    throw AuthErrors.InvalidToken();
  }

  const token = authHeader.substring(7);
  
  try {
    const auth = getAuth();
    const status = await auth.checkLoginStatus(token);
    
    if (!status.isValid || !status.user) {
      throw AuthErrors.TokenExpired();
    }

    // 将用户信息存储在 context state 中
    ctx.state.user = status.user;
    await next();
  } catch (error) {
    // 重新抛出 AppError 类型的错误
    if (error instanceof Error && error.name === "AppError") {
      throw error;
    }
    // 其他错误统一处理为认证失败
    throw AuthErrors.InvalidToken();
  }
} 